package com.chinadrtv.batch.admin.jobs.ozing.question;

import java.util.Calendar;
import java.util.Date;

import com.chinadrtv.user.model.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.validator.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;

import com.chinadrtv.user.model.UserOzingOrder.OrderStatusType;
import com.chinadrtv.user.service.ozing.OzingService;

public class QuestionProcessor implements ItemProcessor<UserOzingOrder, UserOzingOrder> {
    private static Log log = LogFactory.getLog(QuestionProcessor.class);
    
    @Autowired
    private OzingService ozingService;

    @Override
    public UserOzingOrder process(UserOzingOrder order) throws Exception {
    	log.info("process --> " + order + "\t" + Thread.currentThread().getName());
    	
    	if (order.getCostOzingPoint() == null || order.getCostOzingPoint() == 0) {
			throw new ValidationException("Some bad data for " + null);
		}
    	UserOzingBalance balance = ozingService.findOzingCardPointsByUsername(order.getCreatedBy());
    	long currentCardBalance = (balance == null ? 0 : balance.getCardBalance());
    	
    	// 一天内没有解答的离线问, 将锁定的星币退回(如果星卡过期,则增加一天有效期),order标记为取消
    	order.setOrderStatus(OrderStatusType.OrderStatusType_CANCEL);
    	for (UserOzingOrderDetail detail : order.getOzingOrderDetail()) {
    		if (detail.getUserOzingCardTxs() == null || detail.getUserOzingCardTxs().size() == 0){
    			throw new ValidationException("Some bad data for detail.getUserOzingCardTxs");
    		}
    		
    		Date now = new Date();
    		for (UserOzingCardTx tx : detail.getUserOzingCardTxs()) {
    			UserOzingCard card = tx.getUserOzingCard();
    			
    			if (needDelayExpirationDate(card.getCardExpirationDate())) {
    				delayExpirationDate(card);
    			}
    			card.setCardLockedBalance(card.getCardLockedBalance() - tx.getCostOzingPoint());
    			card.setCardBalance(card.getCardBalance() + tx.getCostOzingPoint());
    			
    			// 异常数据
//    			if (card.getCardLockedBalance() < 0) {
//					log.warn("锁定星币为负值,请检查流程:order-->" + order + " \tcard-->" + card);
//					card.setCardBalance(card.getCardBalance() + card.getCardLockedBalance());
//					card.setCardLockedBalance(0);
//				}
    			
    			
    			// cardtx
                UserOzingCardTx txNew = new UserOzingCardTx();
    			txNew.setCostOzingPoint(-tx.getCostOzingPoint());
                txNew.setCreatedBy("system");
                txNew.setDateAdded(now);
                txNew.setLastModified(now);
                txNew.setUpdateBy("system");
                txNew.setTxType(OzingTxType.REFUND);
                
                currentCardBalance += tx.getCostOzingPoint();
                txNew.setTotalBalance(currentCardBalance);
                txNew.setRemark("REFUND");
                card.getOzingCartTx().add(txNew);
                txNew.setUserOzingCard(card);
                txNew.setOzingOrderDetail(detail);
    		}
    	}
    	
        return order;
    }

	private void delayExpirationDate(UserOzingCard card) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		card.setCardExpirationDate(calendar.getTime());
	}

	private boolean needDelayExpirationDate(Date cardExpirationDate) {
		Calendar calendar = Calendar.getInstance();
		
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		Date max = calendar.getTime();
		
		if (cardExpirationDate.after(max)) {
			return false;
		}
		
		calendar.add(Calendar.DAY_OF_MONTH, -2);
		Date limit = calendar.getTime();
		
		// 当前卡的有效期小于一天( now -1 < data < now + 1 ),则增加有效期
		return limit.before(cardExpirationDate);
	}

	public void setOzingService(OzingService ozingService) {
		this.ozingService = ozingService;
	}
	
}
